var render = require('json-templater/string');
var f = require('./utils/uppercamelcase');
var endOfLine = require('os').EOL;

var apiTemplate = require('./templates/api');
var entryTemplate = require('./templates/entry');
var categoryTemplate = require('./templates/category');
var requestTemplate = require('./templates/request');
var date = require('./utils/date');

module.exports.formatEntry = function(entries) {
  var importer = entries.map((name) => `import ${name} from './${name}';`).join(endOfLine);
  var modules = entries.map((name) => `this.${name} = new ${name}(request);`).join(endOfLine + '    ');
  return render(entryTemplate, {
    now: date.getDate(),
    importer: importer,
    modules: modules
  });
};

/**
 * 格式化接口模块信息
 */
module.exports.formatApi = function(_basePath) {
  var basePath = _basePath;
  //兼容后端path后面加 / 的情况
  if (basePath.charAt(basePath.length - 1) === '/') {
    basePath = basePath.substr(0, basePath.length - 1);
  }
  var api = basePath.split('/').reverse()[0];
  return f(api);
};
/**
 * 格式化接口模块地址信息
 */
module.exports.formatApiPath = function(_basePath) {
  var basePath = _basePath;
  //兼容后端path后面加 / 的情况
  if (basePath.charAt(basePath.length - 1) === '/') {
    basePath = basePath.substr(0, basePath.length - 1);
  }
  var apiPath = '/' + basePath.split('/').reverse()[0];
  return apiPath;
};

/**
 * 格式化接口模块内容信息
 */
module.exports.formatApiContent = function(apiname, categories) {
  var categoryContent = [];
  var importerContent = [];
  Object.keys(categories).forEach((categoryName) => {
    categoryContent.push(`this.${categoryName} = new ${categoryName}(this.request)`);
    importerContent.push(`import ${categoryName} from './${categoryName}';`);
  });
  return render(apiTemplate, {
    now: date.getDate(),
    apiClassName: apiname,
    importer: importerContent.join(endOfLine),
    categories: categoryContent.join(endOfLine + '  ')
  });
};


/**
 * 格式化参数信息
 * @param {Object} parameters
 */
function formatParameters(parameters) {
  if (!parameters) {
    return '';
  }
  var rtn = [];
  parameters.forEach((parameter) => {
    rtn.push(
      ` * @param {${parameter.type || ''}} ${parameter.required ? '* ' : ''}${
        parameter.name
      } - ${parameter.description || ''}`
    );
  });
  return rtn.join(endOfLine);
}

/**
 * 格式化api方法名
 * @param {String} url
 * @param {String}} method
 * @param {Object} detail
 */
function formatMethodname(url, method) {
  if (url.indexOf('{') >= 0) {
    // restfull形式的参数格式
    var a = url.replace(/\//g, '_');
    a = a.replace(/\{/, 'by_');
    a = a.replace(/\{/g, '');
    a = a.replace(/}/g, '');
    return `${method}${a}`;
  }
  var b = url.replace(/\//g, '_');
  return `${method}${b}`;

}

/**
 * 格式化请求地址
 * @param {String} url
 */
function formatUrl(url) {
  if (url.indexOf('{') >= 0) {
    // restfull形式的参数格式
    var a = url.replace(/\{/g, '"+params.params.');
    a = a.replace(/\}/g, '+"');
    return `${a}`;
  }
  return url;

}

/**
 * 格式化请求方法内容
 * @param {String} url
 * @param {String} method
 * @param {Object} detail
 */
function formatRequest(url, method, detail, apipath) {
  var summary = detail.summary;
  var parameters = formatParameters(detail.parameters);
  var methodname = formatMethodname(url, method, detail);
  var _url = formatUrl(url, detail);
  _url = apipath + _url;
  return render(requestTemplate, {
    summary: summary,
    parameters: parameters,
    methodname: methodname,
    url: _url,
    method: method
  });
}
/**
 * 格式化分类信息
 */
module.exports.formatCategory = function(categoryName, urls, apipath) {
  // console.log(urls);
  var fullUrls = [];
  Object.keys(urls).forEach((url) => {
    var methods = urls[url];
    // let _url = basePath+url;
    var fillMethods = [];
    Object.keys(methods).forEach((method) => {
      var request = formatRequest(url, method, methods[method], apipath);
      // console.log(request);
      fillMethods.push(request);
    });
    fullUrls.push(fillMethods.join(''));
  });

  return render(categoryTemplate, {
    now: date.getDate(),
    categoryClassName: categoryName,
    requests: fullUrls.join(endOfLine)
  });
};